import json
import copy
import time
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *
import logging
import pandas as pd
import requests

theme_event_project_sync_api = Blueprint('theme_event_project_sync_api', __name__)
theme_event_project_api = Blueprint('theme_event_project_api', __name__)
theme_event_project_down_api = Blueprint('theme_event_project_down_api', __name__)


@theme_event_project_api.route('/theme_event_project', methods=['POST'])
def theme_event_project():
    params = json.loads(request.data)
    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'detail':
        query = ThemeEventProject.query.filter_by(project=_project).first()
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic),
            'reward': json.loads(query.reward),
            'localization': json.loads(query.localization)
        }
        result_data['data']['item'] = tmp

    elif _action == 'doc_id_list':
        doc_file_data = GetDocByFilename('personal_theme_event')
        result = []
        for k, v in doc_file_data.items():
            result.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
            })
        return json.dumps(result)

    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']
        if _part == 'basic':
            ThemeEventProject.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'rank':
            theme_event_project_data = ThemeEventProject.query.filter_by(project=_project).first()
            reward = json.loads(theme_event_project_data.reward)
            reward["rank_reward"] = _data
            ThemeEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'user_goal_reward_list':
            theme_event_project_data = ThemeEventProject.query.filter_by(project=_project).first()
            reward = json.loads(theme_event_project_data.reward)
            reward["user_goal_reward_list"] = _data
            ThemeEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'al_goal_reward_list':
            theme_event_project_data = ThemeEventProject.query.filter_by(project=_project).first()
            reward = json.loads(theme_event_project_data.reward)
            reward["al_goal_reward_list"] = _data
            ThemeEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'score_list':
        with open(STATIC_PATH + 'theme_event_project/score_type.json', encoding='UTF-8') as f:
            data = json.load(f)
            _task_list = []
            for i in data:
                _task_list.append({
                    'label': f'{i["rule_id"]} - {i["doc"]["7"]} - {i["points"]} points',
                    'value': i['rule_id']
                })
            return json.dumps(_task_list)
    elif _action == 'event_ui_list':
        with open(STATIC_PATH + 'theme_event_project/event_ui_list.json', encoding='UTF-8') as f:
            data = json.load(f)
            _event_ui_list = []
            for i in data:
                _event_ui_list.append({
                    'label': f'{i["value"]} - {i["label"]}',
                    'value': i['value']
                })
            return json.dumps(_event_ui_list)
    elif _action == 'event_type_list':
        with open(STATIC_PATH + 'theme_event_project/event_type_list.json', encoding='UTF-8') as f:
            data = json.load(f)
            _event_type_list = []
            for i in data:
                _event_type_list.append({
                    'label': f'{i["value"]} - {i["label"]}',
                    'value': i['value']
                })
            return json.dumps(_event_type_list)
    elif _action == 'common_buff_list':
        data = CommonBuff.query.order_by('id').all()
        _common_buff_list = []
        for i in data:
            _common_buff_list.append({
                'label': f'{i.id} - {i.name}',
                'value': i.id
            })
        return json.dumps(_common_buff_list)
    return jsonify(result_data)


@theme_event_project_down_api.route('/theme_event_project_down/<int:is_push>', methods=['GET', 'POST'])
def theme_event_project_down(is_push):
    result = {}

    query = ThemeEventProject.query.order_by('project').all()

    for q in query:
        _project = str(q.project)
        basic = json.loads(q.basic)
        reward = json.loads(q.reward)
        localization = json.loads(q.localization)

        _score_type_list = []
        with open(STATIC_PATH + 'theme_event_project/score_type.json', encoding='UTF-8') as f:
            score_list_data = json.load(f)
        for i in basic['task_list']:
            for j in score_list_data:
                if i == j['rule_id']:
                    _score_type_list.append(j)

        _al_goal_reward_list = []
        for i in reward['al_goal_reward_list']:
            _temp = []
            for j in i:
                _temp.append({
                    'from': 1,
                    'to': j['to'],
                    'reward': RewardToTMysqlNew(j['reward'])
                })
            _al_goal_reward_list.append(_temp)
        _user_goal_reward_list = []
        for i in reward['user_goal_reward_list']:
            _temp = []
            for j in i:
                _temp.append({
                    'from': 1,
                    'to': j['to'],
                    'reward': RewardToTMysqlNew(j['reward'])
                })
            _user_goal_reward_list.append(_temp)
        _rank_reward = []
        for i in reward['rank_reward']:
            _rank_reward.append({
                'from': i['from'],
                'to': i['to'],
                'reward': RewardToTMysqlNew(i['reward'])
            })

        _tag = basic['_tag'] if '_tag' in basic else []

        result[str(_project)] = {
            '_tag': _tag,
            'calendar_conf': {
                'event_type': 3,
                'event_ui': 1,
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': basic['calendar_doc_id'],
                    'info': basic['calendar_doc_id']
                },
                'reward': RewardToTMysqlNew(basic['top_reward']),
                'show_type': 0
            },
            'basic': {
                'event_type': basic['event_type'],
                'event_ui': basic['event_ui'],
                'share_mode': basic['share_mode'],
                'show_contribution_score': basic['show_contribution_score'],
                'show_rank_score': basic['show_rank_score'],
                'limit_score': basic['limit_score']
            },
            'common_buff_pid': basic['common_buff_pid'],
            'calc_score': {
                'limited': {
                    'castle_lv': basic['castle_lv'],
                    'dragon_lv': basic['dragon_lv']
                },
                'score_type_list': _score_type_list
            },
            'capture_dragon': {
                'cycle': basic['cycle'],
                'max_capture_time': basic['max_capture_time'],
                'open': basic['open']
            },
            'localization': localization,
            'reward': {
                'goal_reward': {
                    'al_goal_reward_list': _al_goal_reward_list,
                    'user_goal_reward_list': _user_goal_reward_list
                },
                'rank_reward': {
                    'user_rank_reward': _rank_reward
                },
                'top_reward': RewardToTMysqlNew(basic['top_reward'])
            }
        }

    response = DownLoad('theme_event_project', result, is_push)

    return response


@theme_event_project_sync_api.route('/theme_event_project_sync', methods=['GET', 'POST'])
def theme_event_project_sync():
    reward_list = rewardList()

    def RewardShowToDocBonus3(reward_list, reward_item_list={}):
        if len(reward_item_list) == 0:
            reward_item_list = rewardList()
        result_bonus = []
        for x in range(len(reward_list)):
            item_type = reward_list[x]['a'][0]
            item_id = reward_list[x]['a'][1]
            item_num = reward_list[x]['a'][2]
            # print(item_type in reward_item_list)
            if item_type in reward_item_list['name'] and str(item_id) in reward_item_list['name'][item_type]:
                item_name = reward_item_list['name'][item_type][str(item_id)]
                item_price = 0
                for z in reward_item_list['reward'][item_type]:
                    if z['id'] == int(item_id):
                        item_price = z['price']
                        break
            else:
                item_name = 'ERROR'
                item_price = 0
            # tmp = {"id": item_id, "name": str(item_id) + ' - ' + item_name, "num": item_num, "price": item_price, "type": item_type}
            tmp = {"id": item_id, "name": item_name, "num": item_num, "price": item_price, "type": item_type}
            result_bonus.append(tmp)
        return result_bonus
    def get_reward_info(r, index):
        if len(r) < index + 1:
            return []
        result = RewardShowToDocBonus3(r[index], reward_list)
        return result

    data = {}
    with open(STATIC_PATH + '../sync/theme_event_project_preprocessing.json', encoding='utf8') as f:
        data = json.load(f)
    print('data length:', len(data))
    _currentIndex = 0
    for i in data:
        _currentIndex += 1
        print('handler: ' + str(_currentIndex) + ' / ' + str(len(data)))
        _project = int(i)
        _basic = data[i]['basic']
        _localization = data[i]['localization']
        _remark = str(_project)
        if "1" in _localization:
            if "title" in _localization["1"]:
                _remark = _localization["1"]["title"]

        _basic['castle_lv'] = data[i]['calc_score']['limited']['castle_lv']
        _basic['dragon_lv'] = data[i]['calc_score']['limited']['dragon_lv']
        _basic['cycle'] = data[i]['capture_dragon']['cycle']
        _basic['max_capture_time'] = data[i]['capture_dragon']['max_capture_time']
        _basic['open'] = data[i]['capture_dragon']['open']
        _basic['calendar_doc_id'] = data[i]['calendar_conf']['localization']['title']
        _basic['common_buff_pid'] = data[i]['common_buff_pid']

        _reward = {
            "rank_reward": [],
            "al_goal_reward_list": [],
            "user_goal_reward_list": [],
            "task_desc": []
        }
        _basic['top_reward'] = RewardShowToDocBonus3(data[i]['reward']['top_reward'], reward_list)
        for j in data[i]['reward']['rank_reward']['user_rank_reward']:
            _reward['rank_reward'].append({"reward": RewardShowToDocBonus3(j['reward'], reward_list), 'from': j['from'], 'to': j['to']})
        for j in data[i]['reward']['goal_reward']['al_goal_reward_list']:
            _temp = []
            for k in j:
                _temp.append({"reward": RewardShowToDocBonus3(k['reward'], reward_list), 'to': k['to']})
            _reward['al_goal_reward_list'].append(_temp)
        for j in data[i]['reward']['goal_reward']['user_goal_reward_list']:
            _temp = []
            for k in j:
                _temp.append({"reward": RewardShowToDocBonus3(k['reward'], reward_list), 'to': k['to']})
            _reward['user_goal_reward_list'].append(_temp)

        _task_list = []
        for j in data[i]['calc_score']['score_type_list']:
            _task_list.append(j['rule_id'])
        _basic['task_list'] = _task_list

        # if 'calendar_show_reward' not in _basic:
        #     _basic['calendar_show_reward'] = []

        if 'limit_score' not in _basic:
            _basic['limit_score'] = 0

        new_project_data = ThemeEventProject(
            project=_project,
            basic=json.dumps(_basic),
            localization=json.dumps(_localization),
            reward=json.dumps(_reward),
            remark=_remark
        )
        db.session.add(new_project_data)
    db.session.commit()
    return jsonify({'msg': 'finished'})
